/**
 * Created by huotaol on 2017/5/10.
 */
import React, {Component} from "react";
import PropTypes from "prop-types";
import {Text, TouchableOpacity, View} from "react-native";

export default class VerifyCodeButton extends Component {
    static propTypes = {
        textStyle: Text.propTypes.style,
        containerStyle: View.propTypes.style,
        activeOpacity: PropTypes.number,
        max: PropTypes.number,
        onStart: PropTypes.func,
        onEnd: PropTypes.func,
        check: PropTypes.func,
    };

    static defaultProps = {
        max: 60,
        disabled: false,
        onStart: () => {
        },
        onEnd: () => {
        },
        check: () => {
            return true;
        }
    };

    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            verifyText: '获取验证码',
            disabled: false,
        };
    }

    render() {
        return (
            <TouchableOpacity
                style={this.props.containerStyle}
                onPress={() => {
                    this._start();
                }}
                disabled={this.state.disabled}
                activeOpacity={this.props.activeOpacity}
            >
                <Text style={this.props.textStyle}>
                    {this.state.verifyText}
                </Text>
            </TouchableOpacity>
        );
    }

    _start() {
        if (this.state.disabled) {
            return;
        }
        if (this.props.check() === false) {
            return;
        }
        this.interval && clearInterval(this.interval);
        this.cd = this.props.max;
        this.interval = setInterval(
            () => {
                this.cd--;
                this.setState({
                    verifyText: this.cd === 0 ? '获取验证码' : this.cd + '秒',
                    disabled: this.cd !== 0,
                });
                if (this.cd === 0) {
                    this.interval && clearInterval(this.interval);
                    this.interval = null;
                    this.props.onEnd();
                }
            }, 1000
        );
        this.props.onStart();
    }
}